<template>
  <div class="base-table-view">
    <!-- 给表格新绑定单元格双击事件 -->
    <el-table ref="baseTable" :data="list" :size="tableSize" tooltip-effect="dark" :border="showBorder" :stripe="stripe" :row-key="getRowKeys" cell-class-name="cellClass" :span-method="isSpanRow && isSpan > 1 && objectSpanMethod" :row-class-name="rowClassName || ''" :height="
        isFixHead &&
          ( fixHeadHeight > 0 ? fixHeadHeight : (list.length > 5 && isFixHead
            ? 200
            : list.length == 0
            ? 180
            : (list.length + 1) * 28.3 + 2.4))
      " @selection-change="handleSelectionChange" header-cell-class-name="headerRow" class="table-main" @sort-change="sortChange" @row-click="handleRowClick" :default-expand-all="expandAll" @expand-change="expandChange" :load="isTreeLazy && load" :lazy="isTreeLazy" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @cell-dblclick="cellDblclick">
      <!-- 多选 -->
      <el-table-column v-if="selection" type="selection" width="55" :reserve-selection="true" :selectable="isMultiDisable && checkSelectable" align="center"></el-table-column>
      <!-- 单选,所有表格只能选一行 -->
      <el-table-column v-if="radio" align="center" width="80">
        <template slot-scope="scope">
          <el-radio class="radio" v-model="radio" :label="scope.$index" @change.native="getCurrentRow(scope.$index, scope.row)">&nbsp;
          </el-radio>
          <!-- :disabled="scope.row.Enable==1?false:true" -->
        </template>
      </el-table-column>
      <el-table-column type="expand" v-if="expand">
        <template slot-scope="props">
          <slot name="expand" :props="props.row"></slot>
        </template>
      </el-table-column>

      <!-- v-for="it in columnList" -->
      <el-table-column v-for="it in titleList" :key="it.prop" :prop="it.prop" :label="it.label" :width="it.width" :min-width="it.minWidth" :align="it.align ? it.align : 'center'" :sortable="it.sort" :show-overflow-tooltip="it.showTip" :header-align="it.headAlign ? it.headAlign : 'center'" :class-name="`${it.prop}-${it.prop}`">
        <!-- :fixed="it.fixed" -->
        <template slot-scope="scope">
          <!-- slot插槽，便于在父组件插入其他东西 -->
          <slot :name="it.prop" :data="scope.row" :index="scope.$index"></slot>
          <span v-if="it.html" v-html="getContent(it, scope.row)" :class="it.prop"></span>
          <span v-else-if="!it.html && it.getData">{{
            getContent(it, scope.row)
          }}</span>
          <ex-slot v-else-if="it.render" :render="it.render" :row="scope.row" :index="scope.$index" :column="it" />
          <span v-else-if="it.render" :render="it.render"></span>
          <span v-else-if="!it.slot">{{ scope.row[it.prop] }}</span>
        </template>
      </el-table-column>
      <!--  -->
      <el-table-column label="操作" :fixed="operateFix" align="center" v-if="actionList.length > 0" :min-width="actionLength * 42">
        <template slot-scope="scope">
          <el-button class="operationButton" v-show="isDropOptions" v-for="x in actionList" :key="x.type" size="small" :type="x.num ? x.types : 'text'" :icon="x.icon" :disabled="judgeOptionDisabled(x, scope.row)" @click.stop="actionClick(scope.row, x.type)" :plain="x.num"><span>{{ x.num ? x.text : "" }}</span></el-button>
          <!--   -->
          <!-- style="color:#11baf7" -->
          <el-dropdown v-if="!isDropOptions">
            <span class="el-dropdown-link" style="font-size: 12px;">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="dropdown-button">
              <el-dropdown-item v-for="x in actionList" :key="x.type">
                <el-button type="text" size="small" @click.stop="actionClick(scope.row, x.type)" :disabled="judgeOptionDisabled(x, scope.row)">{{ x.text }}</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
/**
 * 操作按钮列在表格内部
 * props的数据含义：
 * {boolean} [stripe = true] - 表格斑马纹
 * {object[]} list - 表格数组
 * {object[]} titleList - 表格头部数组
 * {boolean} [selection = false]  表格多选框是否显示，默认值是false，不显示多选框
 * {boolean} [showBorder = false] - 表格是否需要边框，默认值是true，需要边框
 * {object[]} actionList - 操作列数组
 * actionList = [{cName: '编辑', eName: 'edit', type: 'primary'}]
 */
var exSlot = {
  functional: true,
  props: {
    row: Object,
    render: Function,
    index: Number,
    column: {
      type: Object,
      default: null
    }
  },
  render: (h, data) => {
    const params = {
      row: data.props.row,
      index: data.props.index
    };
    if (data.props.column) params.column = data.props.column;
    return data.props.render(h, params);
  }
};
export default {
  components: { exSlot },
  props: {
    list: {
      type: Array,
      default: () => []
    },

    titleList: {
      type: Array,
      default: () => []
    },
    rowClassName: {
      type: [String, Function],
      default: ""
    },
    expand: {
      type: Boolean,
      defalult: false
    },

    selection: {
      type: Boolean,
      defalult: false
    },
    radio: {
      type: Boolean,
      defalult: false
    },
    showBorder: {
      type: Boolean,
      default: true
    },

    actionList: {
      type: Array,
      default: () => []
    },
    stripe: {
      type: Boolean,
      default: false
    },
    // 是否展示button按钮，弹出列选择
    isChangeColumn: {
      type: Boolean,
      defalult: true
    },
    // 表格右侧是否展开折叠，默认展开，当没有搜索的时候是不展开的
    isShowCollopse: {
      type: Boolean,
      default: true
    },
    // 树形表格是否全部展开
    expandAll: {
      type: Boolean,
      default: false
    },
    // 为了区分字典页面的父级和自己页面批量操作点击事件
    pageParent: {
      type: Boolean,
      default: true
    },
    isMultiDisable: {
      type: Boolean,
      default: false
    },
    isSpanRow: {
      type: Boolean, // 是否合并行列
      default: false
    },
    indexInfoList: {
      type: Array,
      defalult: () => []
    },
    indexList: {
      type: Array,
      defalult: () => []
    },
    isSpan: {
      type: Number,
      defalult: 0
    },
    isGenerate: {
      type: Boolean,
      default: false
    },
    checkId: {
      type: String,
      default: "id"
    },
    // 是否固定表头
    isFixHead: {
      type: Boolean,
      default: false
    },
    fixHeadHeight: {
      type: Number,
      default: 0
    },
    isTreeLazy: {
      type: Boolean,
      default: false
    },
    operateFix: {
      type: [Boolean, String],
      default: "right"
    },
    tableSize: {
      type: String,
      default: "mini"
    },
    isDropOptions: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      // isOpen: false,
      title: "",
      drawer: false,
      columnList: [],
      actionMinWidth: "",
      // 是否展示table上面的所有内容
      isOpen: true,
      radio: ""
    };
  },
  mounted() {
    // this.tableHeaderInit(this.titleList);
  },
  computed: {
    // 获取操作列数组的长度，根据数组的长度给表格操作列设置宽度
    actionLength() {
      let sum = 0;
      this.actionList.forEach(it => {
        sum += it.text.length;
      });
      return sum;
    }
    // ...mapGetters(['roleName'])
  },
  watch: {
    // checkList(val) {
    //   // console.log(val, "va");
    //   this.columnList = this.titleList.filter((it) => val.indexOf(it.key) >= 0);
    // },
    titleList(n) {
      // this.tableHeaderInit(n);
    }
  },

  methods: {
    getCurrentRow(index, row) {
      this.radio = index;
      //  这里可以向上传递事件，方便父组件操作
    },
    getContent(header, row) {
      return header.getData(row) || "";
    },
    // 判断表格操作列按钮是否禁掉
    judgeOptionDisabled(x, row) {
      if (x.type == "download" && !row.eventFileName) {
        return true;
      }
    },
    // 当前行的唯一标识，用户多选记忆功能
    getRowKeys(row) {
      let id = this.checkId;
      // console.log(this.checkId)
      return row[id];
    },
    tableHeaderInit(n) {
      let arr = [];
      n.forEach((it, index) => {
        it.key = it.prop;
        // 隐藏英文名称，只展示中文名称
        if (!it.isHidden) {
          arr.push(it.key);
        }
      });
      // this.checkList = arr;
    },
    /**
     * @description 操作按钮事件
     * @param {string} a - 操作类型
     * @param {object} b - 操作行
     */
    actionClick(a, b) {
      this.$emit("action", { type: b, row: a });
    },
    handleSelectionChange(val) {
      this.$emit("SelectionChange", val, this.pageParent);
    },
    expandChange(row) {
      this.$emit("expandChange", row);
    },
    closeClick() {
      this.title = "";
      this.drawer = false;
    },
    submit() {
      this.closeClick();
    },
    sortChange(data) {
      this.$emit("sortChange", data);
    },
    handleRowClick(row, column, event) {
      this.$emit("rowClick", row, column, event, this.pageParent);
    },
    leftBtnClick(it) {
      this.$emit("leftBtnClick", it);
    },
    rightBtnClick(it) {
      switch (it.type) {
        case "showColunn":
          this.title = "列显隐";
          this.drawer = true;
          break;
        case "isCloseOpen":
          this.isOpen = !this.isOpen;
          this.$emit("isCloseOpen", this.isOpen, this.pageParent);
          break;
        case "refresh":
          this.$emit("refresh", this.pageParent);
          break;
      }
    },
    // 多选是否需要禁掉
    checkSelectable(row) {
      // mask不可选，只用string才可以选择
      if (row.dataType == "mask" || row.checkState !== '1') {
        return false;
      } else {
        return true;
      }
    },
    selectAll(selection) {
      //  this.$emit("selectAll", selection);
    },
    load(tree, treeNode, resolve) {
      this.$emit("treeLoad", tree, treeNode, resolve);
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(rowIndex, 'row')
      // this.$emit("objectSpanMethod", row, column, rowIndex, columnIndex );
      // let temArr = [this.indexInfoList, this.indexList]
      // if( columnIndex <2){
      //   let index = columnIndex ==0 ?temArr[0].findIndex(item => {return item.firstIndex === rowIndex;}):temArr[1].findIndex(item => {return item.firstIndex === rowIndex;})
      //   if(index > -1){
      //     return {
      //         rowspan: columnIndex ==0 ? temArr[0][index].length:temArr[1][index].length,
      //         colspan: 1
      //     }
      //   }else{
      //     return {
      //         rowspan: 0,
      //         colspan: 0
      //       };
      //   }
      // }

      if (columnIndex === 0) {
        let index = this.indexInfoList.findIndex(item => {
          return item.firstIndex === rowIndex;
        });
        // console.log(index, 'index')
        if (index > -1) {
          return {
            rowspan: this.indexInfoList[index].length,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
      if (columnIndex === 1) {
        let index = this.indexList.findIndex(item => {
          return item.index === rowIndex;
        });
        if (index > -1) {
          return {
            rowspan: this.indexList[index].length,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 双击单元格事件
    cellDblclick(row, column, cell, event) {
      this.$emit("cellDblclick", row, column, cell, event);
    }
  }
};
</script>

<style lang="less" scoped>
.base-table-view {
  /deep/ .el-button--primary.is-plain {
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
  }
  .leftButton {
    margin-bottom: 10px;
  }
  .icon {
    margin-left: 10px;
    color: white;
    font-size: 16px !important;
    padding: 9px !important;
  }
  .operationButton {
    margin-right: 0px;
    border-radius: 4px;
  }
  .el-button.el-button--primary {
    width: 75px;
    height: 34px;
  }
}
</style>
